import * as crypto from 'crypto';
import fetch from 'node-fetch';
import * as qs from 'querystring';

const AK = 'A330000100000202105004227';
const SK = 'e57ae75ea2bf4d2fa45bb619a0710d01';

let _refreshSecret = null;
let _requestSecret = null;

function getMd5(value) {
    return crypto.createHash('md5').update(value).digest('hex');
}

function getSign(secret) {
    const time = new Date().valueOf();
    const sign = getMd5(`${AK}${secret}${time.toString()}`);
    return {
        requestTime: time.toString(),
        sign: sign,
        appKey: AK,
    };
}


async function refreshTokenByKey() {
    const params = getSign(SK);
    const rep = await fetch(
        'https://datashare.etz.gov.cn/gateway/app/refreshTokenByKey.htm',
        {
            method: 'POST',
            body: qs.stringify(params),
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
            },
        },
    )
        .then((p) => p.json())
        .catch((e) => {
            console.log(e);
        });
    console.log('refreshTokenByKey', rep);
    if (rep.code === '00') {
        const {
            refreshSecret,
            refreshSecretEndTime,
            requestSecret,
            requestSecretEndTime,
        } = rep.datas;

        _refreshSecret = refreshSecret;
        _requestSecret = requestSecret;

        setTimeout(()=> {
            _requestSecret = null;
        },12 * 60 * 1000)

        setTimeout(()=> {
            _refreshSecret = null;
        },refreshSecretEndTime - new Date().valueOf() - 60000)

        return requestSecret;
    }

    return null;
}


async function refreshTokenBySec() {
    if(_requestSecret) {
        return _requestSecret;
    } else if(_refreshSecret) {
        const params = getSign(_refreshSecret);
        const result = await fetch(
            'https://datashare.etz.gov.cn/gateway/app/refreshTokenBySec.htm',
            {
                method: 'POST',
                body: qs.stringify(params),
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
            },
        )
            .then((p) => p.json())
            .catch((e) => {
                console.log(e);
            });

        if (result.code === '00') {
            const { refreshSecret, refreshSecretEndTime, requestSecret } =
                result.datas;

            setTimeout(()=> {
                _requestSecret = null;
            },12 * 60 * 1000)

            setTimeout(()=> {
                _refreshSecret = null;
            },refreshSecretEndTime - new Date().valueOf() - 60000)

            return requestSecret;
        }

        return null;
    } else {
        return refreshTokenByKey();
    }


}


export async function irsSearch(url, where) {
    const secret = await refreshTokenBySec();
    const params = getSign(secret);

    const query = {
        ...where,
        ...params,
    };

    const result = await fetch(url, {
        method: 'POST',
        body: qs.stringify(query),
        headers: {
            'content-type': 'application/x-www-form-urlencoded',
        },
    })
        .then((p) => p.json())
        .catch((e) => {
            if (e) {
                console.log(e);
            }
        });

    if (result.code === '00') {
        console.log('请求IRS成功！');
        return JSON.parse(result.datas);
    } else {
        console.error(result.msg);
    }
    return null;
}
